
package org.brainstretch.models.quizzes;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import org.codehaus.jackson.annotate.JsonIgnore;

/**
 * A QuizInstance object is a single version of a quiz meant to be displayed and taken by a user.
 * Questions are chosen from each available question set and put in a random order (if that option is selected)
 * @author mrodaitis
 */
@XmlRootElement
@Entity
public class QuizInstance implements Serializable{
    
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;
    
    @ManyToMany
    private List<Question> questions;
    
    @XmlTransient
    @ManyToOne
    private Quiz quiz;
    
    @Column(length=255)
    private String authToken;
    
    private int duration;
    
    public QuizInstance(Quiz quiz) {
        this.quiz = quiz;
        questions = chooseQuestions(quiz);
        this.duration = quiz.getDuration();
    }
    
    public QuizInstance(){
        
    }
    
    
    private List<Question> chooseQuestions(Quiz quiz){
        Random random = new Random();
        List<Question> selectedQuestions = new ArrayList<Question>();
        for(QuestionSet questionSet: quiz.getQuestionSets()){
            Question randomQuestion = chooseQuestionFromSet(questionSet, random);
            if(randomQuestion != null){
                selectedQuestions.add(randomQuestion);
            }
        }        
        return selectedQuestions;        
    }
    
    private Question chooseQuestionFromSet(QuestionSet questionSet, Random random){
        Question chosen = null;
        List<Question> setQuestions = questionSet.getQuestions();
        if(! setQuestions.isEmpty()){
            chosen = setQuestions.get(random.nextInt(setQuestions.size()));
        }
        return chosen;
    }

    public String getAuthToken() {
        return authToken;
    }

    public void setAuthToken(String authToken) {
        this.authToken = authToken;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }   

    public List<Question> getQuestions() {
        return questions;
    }

    public void setQuestions(List<Question> questions) {
        this.questions = questions;
    }

    @JsonIgnore
    public Quiz getQuiz() {
        return quiz;
    }

    public void setQuiz(Quiz quiz) {
        this.quiz = quiz;
    }

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }
}
